"use strict";
require( '../../../config' );
var fs = require('fs'),
    assert = require('assert'),
    vpnModel = require('../../../../app/components/backend/db/models/vpn'),
    helper      = require('../../../helper'),
    weixin = require('../../../../app/components/backend/service/weixin');

describe('app/components/backend/service/weixin', function () {

  beforeEach(function () {
    return helper.initVpn();
  });

  // 测试后置处理
  afterEach(function() {

    // 复位
    vpnModel.remove({}, function (err) {
      if (err) throw new Error(err);
      Promise.resolve();
    });
  });
  describe('#processMessage()', function () {
    var testData = fs.readFileSync('test/components/backend/service/admin_vpn_data.xml').toString();
    var removeData = fs.readFileSync('test/components/backend/service/admin_vpn_remove_data.xml').toString();
    var listvpnData = testData.replace('<![CDATA[192.168.12.55,xxxxxxxxxx]]>', '<![CDATA[listvpn]]>');
    var helpData = testData.replace('<![CDATA[192.168.12.55,xxxxxxxxxx]]>', '<![CDATA[help]]>');
    it('[processMessage.admin.vpn.Nor.01].admin添加/修改vpn', function () {
      return weixin.processMessage(testData).then(function (upsertMsg) {
        assert.ok(upsertMsg.action_type, 'admin_vpn');
        assert.ok(upsertMsg.msg.indexOf('更新成功') > 0);
      }).then(weixin.processMessage.bind(weixin, removeData)).then(function (removeMsg) {
        assert.ok(removeMsg.action_type, 'admin_vpn');
        assert.ok(removeMsg.msg.indexOf('删除成功') > 0);
      }).then(vpnModel.find(function (vpn) {
        assert.equal(vpn, null);
      }));
    });

    it('[processMessage.admin.vpn.Nor.02].admin listvpn', function () {
      return helper.prepareVpnData()
        .then(weixin.processMessage.bind(weixin, listvpnData))
        .then(function (listvpnMsg) {
          assert.ok(listvpnMsg.action_type, 'admin_vpn');
          assert.ok(listvpnMsg.msg.indexOf('目前可用vpn服务器如下: \r\n\
192.168.12.55\r\n\
192.168.12.100\r\n\
192.168.12.212\r\n') > 0);
        });
    });

    it('[processMessage.admin.vpn.Nor.03].admin help', function () {
      return weixin.processMessage(helpData)
        .then(function (helpMsg) {
          assert.ok(helpMsg.action_type, 'admin_vpn');
          assert.ok(helpMsg.msg.indexOf('管理员你好！\r\n\
你可以发送如下消息管理vpn服务器\r\n\
1. 输入 help 获得帮助\r\n\
2. 输入 listvpn 获得当前可用vpn服务器列表\r\n\
3. 输入 [vpn服务器的ip地址] 删除vpn服务器\r\n\
4. 输入 [vpn服务器地址],[vpn密码] 添加或更新vpnu服务器') > 0);
        });
    });
  });
});